#include "Game_page.h"
#include "IniProgram.h"
#include "Container.h"
#include "Snake.h"
#include "FoodManager.h"

#include <iostream>
#include <cmath>
#include <memory>
using namespace std;

extern ClotherType ClothingType;

Container *Game_Page = nullptr;
unique_ptr<Snake> gameSnake = nullptr;

Container *Joystick = nullptr;
Container *Joystick_center = nullptr;
Container *Menu_Btn = nullptr;
Container *Refresh_Btn = nullptr;

unique_ptr<FoodManager> foodManager = nullptr;

int foodcount = 75;
bool bj = true;

void Display_Game_Page()
{
    manager.set_top(Game_Page);
}

void gameStart()
{
    if (gameSnake->isMove())
        return;
    if (gameSnake != nullptr)
    {
        gameSnake->startMoving(); // 现在这个调用是安全的
    }
}

void gameStop()
{
    manager.set_top(Menu_Page);

    if (!gameSnake->isMove())
        return;
    if (gameSnake != nullptr)
    {
        gameSnake->stopMoving();
    }
}

void reStart()
{
    Game_Page->set_background_image("./res/background.bmp");

    // 3. 创建新蛇对象
    gameSnake = std::make_unique<Snake>(Game_Page, 30, 15, 5, 150, ClothingType);

    foodManager->clearAllFood();

    // 4. 重置食物管理器（智能指针会自动释放旧对象）
    foodManager = std::make_unique<FoodManager>(Game_Page, foodcount, 30);

    // 5. 生成初始食物
    for (int i = 0; i < foodcount; i++)
    {
        foodManager->generateRandomFood(*gameSnake);
    }
}

void IniGame()
{
    // 创建食物管理器
    foodManager = std::make_unique<FoodManager>(Game_Page, foodcount, 30);
}

void create_Game_Page()
{
    // 创建主容器
    Game_Page = new Container(800, 480);
    Game_Page->set_background_image("./res/background.bmp");
    Game_Page->set_Visible(true);
    Game_Page->set_Event_Type(CLICK);
    // Game_Page->set_Event(gameStart);

    // 创建摇杆
    Joystick = new Container(Game_Page, 200, 200);
    Joystick->align(BOTTOM_LEFT, 20, -20);
    Joystick->set_background_image("./res/joystick.bmp", true, 0x00ffffff);
    Joystick->set_Event_Type(LONG_PRESS);
    Joystick->set_Visible(true);
    Joystick->set_Event(Joystick_touch);

    Joystick_center = new Container(Joystick, 50, 50);
    Joystick_center->align(CENTER);
    Joystick_center->set_Visible(true);
    Joystick_center->set_background_image("./res/joystick_center.bmp", true, 0x00ffffff);

    // 创建暂停/开始按钮
    Menu_Btn = new Container(Game_Page, 50, 50);
    Menu_Btn->set_background_image("./res/menu.bmp", true, 0x00ffffff);
    Menu_Btn->set_Visible(true);
    Menu_Btn->align(TOP_LEFT, 10, 10);
    Menu_Btn->set_Event_Type(PRESS);
    Menu_Btn->set_Event(gameStop);

    IniGame();

    // 添加到管理器
    manager.add(Game_Page);

    cout << "贪吃蛇游戏初始化完成" << endl;
    cout << "点击红色按钮重新开始游戏" << endl;
}
